// 1. React核心库
import React, { useState, useRef } from 'react';

// 2. UI组件库 - 按字母顺序排列
import {
  Button,
  Tag,
  message,
  Popconfirm,
  Tooltip,
  Typography,
  Modal,
  Form,
  Tabs,
  Transfer,
} from 'antd';

// 3. 图标库
import {
  UserOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  StopOutlined,
  CheckCircleOutlined,
  ReloadOutlined,
  CrownOutlined,
  SettingOutlined,
  KeyOutlined,
  SaveOutlined,
} from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable, ProForm, ProFormText, ProFormSwitch } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';

// 5. 工具库
import { history, useAccess } from '@umijs/max';

// 6. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 7. 生成的类型定义 (必须使用，禁止手工定义)
import type {
  UserList,
  PaginatedUserListList,
  UserDetail,
  BulkDeleteRequest,
  UserUpdateRequest
} from '@/services/generated/src/index';

// 解构常用子组件
const { Text } = Typography;

const UserListNew: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [toggleLoading, setToggleLoading] = useState(false);
  const [bulkDeleteLoading, setBulkDeleteLoading] = useState(false);

  // 编辑相关状态
  const [editVisible, setEditVisible] = useState(false);
  const [editLoading, setEditLoading] = useState(false);
  const [editingUser, setEditingUser] = useState<UserList | null>(null);
  const [editForm] = Form.useForm();
  const [activeTab, setActiveTab] = useState('basic');

  // 权限和组管理状态
  const [allPermissions, setAllPermissions] = useState<any[]>([]);
  const [allGroups, setAllGroups] = useState<any[]>([]);
  const [selectedPermissions, setSelectedPermissions] = useState<number[]>([]);
  const [selectedGroups, setSelectedGroups] = useState<number[]>([]);
  const [transferLoading, setTransferLoading] = useState(false);

  const actionRef = useRef<ActionType>();
  const access = useAccess();

  // � 保存用户组分配
  const handleSaveUserGroups = async () => {
    if (!editingUser) return;

    try {
      setEditLoading(true);

      // 🔑 关键：直接使用Django标准的groups字段更新
      await apiClients.users.usersPartialUpdate({
        id: editingUser.id,
        patchedUserUpdateRequest: {
          groups: selectedGroups
        }
      });

      message.success('用户组分配保存成功');
      actionRef.current?.reload();

      // 重新加载用户数据以更新界面
      await loadUserEditData(editingUser.id);
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error?.message || '保存组分配失败';
      message.error(errorMessage);
    } finally {
      setEditLoading(false);
    }
  };

  // 💾 保存用户权限分配
  const handleSaveUserPermissions = async () => {
    if (!editingUser) return;

    try {
      setEditLoading(true);

      // 🔑 关键：直接使用Django标准的user_permissions字段更新
      await apiClients.users.usersPartialUpdate({
        id: editingUser.id,
        patchedUserUpdateRequest: {
          user_permissions: selectedPermissions
        }
      });

      message.success('用户权限分配保存成功');
      actionRef.current?.reload();

      // 重新加载用户数据以更新界面
      await loadUserEditData(editingUser.id);
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error?.message || '保存权限分配失败';
      message.error(errorMessage);
    } finally {
      setEditLoading(false);
    }
  };

  // �📋 加载用户编辑数据
  const loadUserEditData = async (userId: number) => {
    try {
      setTransferLoading(true);

      // 并行加载所有数据
      const [userResponse, permissionsResponse, groupsResponse] = await Promise.all([
        apiClients.users.usersRetrieve({ id: userId }),
        apiClients.permissions.permissionsPermissionsList({ pageSize: 1000 }),
        apiClients.permissions.permissionsGroupsList({ pageSize: 1000 })
      ]);

      // 处理响应数据
      const userData = (userResponse as any).data || userResponse;
      const allPermissionsData = ((permissionsResponse as any).data || permissionsResponse).items || [];
      const allGroupsData = ((groupsResponse as any).data || groupsResponse).items || [];

      console.log('🔍 用户编辑数据加载结果:', {
        userData,
        allPermissionsCount: allPermissionsData.length,
        allGroupsCount: allGroupsData.length,
        userGroups: userData.groups,
        userPermissions: userData.user_permissions,
        groupNames: userData.group_names,
        permissionNames: userData.permission_names
      });

      // 设置数据
      setAllPermissions(allPermissionsData);
      setAllGroups(allGroupsData);

      // 🔑 关键：现在groups和user_permissions字段直接返回ID列表
      const userGroupIds = userData.groups || [];
      const userPermissionIds = userData.user_permissions || [];

      console.log('🎯 设置用户组ID:', userGroupIds);
      console.log('🎯 设置用户权限ID:', userPermissionIds);

      setSelectedGroups(userGroupIds);
      setSelectedPermissions(userPermissionIds);

    } catch (error: any) {
      console.error('❌ 加载用户编辑数据失败:', error);
      message.error('加载数据失败');
    } finally {
      setTransferLoading(false);
    }
  };

  // ✏️ 开始编辑用户
  const handleStartEdit = async (record: UserList) => {
    if (!access.canUpdateUser) {
      message.error('没有编辑用户的权限');
      return;
    }

    try {
      setEditingUser(record);
      editForm.setFieldsValue({
        username: record.username,
        email: record.email,
        first_name: record.first_name || '',
        last_name: record.last_name || '',
        is_active: record.is_active,
        is_staff: record.is_staff,
      });
      setEditVisible(true);
      setActiveTab('basic');

      // 加载权限和组数据
      await loadUserEditData(record.id);
    } catch (error) {
      message.error('打开编辑窗口失败');
    }
  };

  // 💾 保存编辑
  const handleSaveEdit = async (values: any) => {
    if (!editingUser) return;

    try {
      setEditLoading(true);

      // 1. 更新基本信息
      await apiClients.users.usersPartialUpdate({
        id: editingUser.id,
        patchedUserUpdateRequest: {
          email: values.email,
          first_name: values.first_name,
          last_name: values.last_name,
          is_active: values.is_active,
          is_staff: values.is_staff,
        }
      });

      // 2. 更新用户组（如果有变化）
      // TODO: 实现用户组分配API调用

      // 3. 更新用户权限（如果有变化）
      // TODO: 实现用户权限分配API调用

      message.success('用户信息更新成功');
      setEditVisible(false);
      setEditingUser(null);
      editForm.resetFields();
      setActiveTab('basic');
      actionRef.current?.reload();
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error?.message || '更新失败';
      message.error(errorMessage);
    } finally {
      setEditLoading(false);
    }
  };

  // 🗑️ 删除单个用户
  const handleDelete = async (userId: number) => {
    if (!access.canDeleteUser) {
      message.error('没有删除用户的权限');
      return;
    }

    try {
      setDeleteLoading(true);
      await apiClients.users.usersDestroy({ id: userId });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error?.message || '删除失败';
      message.error(errorMessage);
    } finally {
      setDeleteLoading(false);
    }
  };

  // 🔄 切换用户状态
  const handleToggleStatus = async (userId: number, isActive: boolean) => {
    if (!access.canUpdateUser) {
      message.error('没有修改用户状态的权限');
      return;
    }

    try {
      setToggleLoading(true);
      await apiClients.users.usersToggleStatusCreate({
        id: userId,
        userStatusRequest: { is_active: !isActive }
      });
      message.success(isActive ? '用户已禁用' : '用户已激活');
      actionRef.current?.reload();
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error?.message || '操作失败';
      message.error(errorMessage);
    } finally {
      setToggleLoading(false);
    }
  };

  // 👑 切换管理员权限
  const handleToggleStaff = async (userId: number) => {
    try {
      await apiClients.users.usersToggleStaffCreate({ id: userId });
      message.success('权限设置成功');
      actionRef.current?.reload();
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error?.message || '操作失败';
      message.error(errorMessage);
    }
  };

  // 🔑 重置密码
  const handleResetPassword = async (userId: number) => {
    Modal.confirm({
      title: '重置密码',
      content: '确定要重置该用户的密码吗？新密码将通过邮件发送给用户。',
      onOk: async () => {
        try {
          await apiClients.users.usersResetPasswordCreate({
            id: userId,
            userPasswordResetRequest: {
              new_password: 'TempPass123!',
              reason: '管理员重置'
            }
          });
          message.success('密码重置成功');
        } catch (error: any) {
          const errorMessage = error?.response?.data?.message || error?.message || '重置失败';
          message.error(errorMessage);
        }
      }
    });
  };

  // 🗑️ 批量删除用户
  const handleBulkDelete = async () => {
    if (!access.canDeleteUser) {
      message.error('没有删除用户的权限');
      return;
    }

    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的用户');
      return;
    }

    Modal.confirm({
      title: '批量删除用户',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个用户吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          setBulkDeleteLoading(true);
          await apiClients.users.usersBulkDeleteCreate({
            bulkDeleteRequest: {
              ids: selectedRowKeys.map(key => Number(key)),
              reason: '批量删除操作'
            }
          });
          message.success(`成功删除 ${selectedRowKeys.length} 个用户`);
          setSelectedRowKeys([]);
          actionRef.current?.reload();
        } catch (error: any) {
          const errorMessage = error?.response?.data?.message || error?.message || '批量删除失败';
          message.error(errorMessage);
        } finally {
          setBulkDeleteLoading(false);
        }
      }
    });
  };

  // 📋 表格列定义
  const columns: ProColumns<UserList>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
      sorter: true,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 120,
      copyable: true,
      ellipsis: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: 200,
      copyable: true,
      ellipsis: true,
    },
    {
      title: '全名',
      dataIndex: 'full_name',
      width: 120,
      search: false,
      ellipsis: true,
    },
    {
      title: '用户状态',
      dataIndex: 'status_display',
      width: 120,
      search: false,
      render: (_, record) => {
        let color = 'blue';
        let icon = <UserOutlined />;
        
        if (!record.is_active) {
          color = 'default';
          icon = <StopOutlined />;
        } else if (record.is_superuser) {
          color = 'purple';
          icon = <CrownOutlined />;
        } else if (record.is_staff) {
          color = 'orange';
          icon = <SettingOutlined />;
        }

        return (
          <Tag color={color} icon={icon}>
            {record.status}
          </Tag>
        );
      },
    },
    {
      title: '是否激活',
      dataIndex: 'is_active',
      width: 100,
      valueType: 'select',
      valueEnum: {
        true: { text: '激活', status: 'Success' },
        false: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '管理员',
      dataIndex: 'is_staff',
      width: 100,
      valueType: 'select',
      valueEnum: {
        true: { text: '是', status: 'Success' },
        false: { text: '否', status: 'Default' },
      },
    },
    {
      title: '超级用户',
      dataIndex: 'is_superuser',
      width: 100,
      search: false,
      render: (_, record) => (
        record.is_superuser ? (
          <Tag color="purple" icon={<CrownOutlined />}>是</Tag>
        ) : (
          <Tag color="default">否</Tag>
        )
      ),
    },
    {
      title: '注册时间',
      dataIndex: 'date_joined',
      width: 180,
      valueType: 'dateTime',
      search: false,
      sorter: true,
    },
    {
      title: '最后登录',
      dataIndex: 'last_login_display',
      width: 180,
      search: false,
      ellipsis: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: (_, record) => [
        <Tooltip key="view" title="查看详情">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => history.push(`/users/detail/${record.id}`)}
          />
        </Tooltip>,
        
        access.canUpdateUser && (
          <Tooltip key="edit" title="编辑用户">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleStartEdit(record)}
            />
          </Tooltip>
        ),

        access.canUpdateUser && (
          <Tooltip key="toggle" title={record.is_active ? '禁用用户' : '激活用户'}>
            <Button
              type="link"
              size="small"
              loading={toggleLoading}
              icon={record.is_active ? <StopOutlined /> : <CheckCircleOutlined />}
              onClick={() => handleToggleStatus(record.id, record.is_active || false)}
            />
          </Tooltip>
        ),

        access.canUpdateUser && (
          <Tooltip key="reset-password" title="重置密码">
            <Button
              type="link"
              size="small"
              icon={<KeyOutlined />}
              onClick={() => handleResetPassword(record.id)}
            />
          </Tooltip>
        ),

        // 只有超级用户可以设置管理员权限
        access.hasPermission && access.hasPermission('auth.change_user') && (
          <Tooltip key="toggle-staff" title="切换管理员权限">
            <Button
              type="link"
              size="small"
              icon={<CrownOutlined />}
              onClick={() => handleToggleStaff(record.id)}
            />
          </Tooltip>
        ),

        access.canDeleteUser && !record.is_superuser && (
          <Popconfirm
            key="delete"
            title="确定删除此用户吗？"
            description="此操作不可恢复"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除用户">
              <Button
                type="link"
                size="small"
                danger
                loading={deleteLoading}
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        ),
      ].filter(Boolean),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '用户管理',
        breadcrumb: {
          items: [
            { title: '首页', path: '/' },
            { title: '用户管理', path: '/users' },
            { title: '用户列表' },
          ],
        },
      }}
    >
      <ProTable<UserList>
        columns={columns}
        actionRef={actionRef}
        request={async (params, sort) => {
          try {
            await autoLoginInDev(); // 开发环境自动登录

            // 处理排序参数
            let ordering = undefined;
            if (sort && Object.keys(sort).length > 0) {
              const sortField = Object.keys(sort)[0];
              const sortOrder = sort[sortField];
              ordering = sortOrder === 'ascend' ? sortField : `-${sortField}`;
            }

            const response = await apiClients.users.usersList({
              page: params.current || 1,
              pageSize: params.pageSize || 20,
              search: params.username || params.email,
              isActive: params.is_active,
              isStaff: params.is_staff,
              isSuperuser: params.is_superuser,
              ordering,
            });

            console.log('🚀 用户列表API响应:', response);

            // 🔑 关键：正确提取分页数据
            const responseData = (response as any).data || response;
            
            return {
              data: responseData.items || [],
              success: true,
              total: responseData.total || 0,
            };
          } catch (error: any) {
            console.error('❌ 获取用户列表失败:', error);
            message.error('获取用户列表失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
        }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
          getCheckboxProps: (record) => ({
            disabled: record.is_superuser, // 超级用户不能被选中删除
          }),
        }}
        toolBarRender={() => [
          access.canCreateUser && (
            <Button
              key="create"
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => history.push('/users/create')}
            >
              新建用户
            </Button>
          ),
          
          selectedRowKeys.length > 0 && access.canDeleteUser && (
            <Button
              key="bulk-delete"
              danger
              loading={bulkDeleteLoading}
              icon={<DeleteOutlined />}
              onClick={handleBulkDelete}
            >
              批量删除 ({selectedRowKeys.length})
            </Button>
          ),
          
          <Button
            key="refresh"
            icon={<ReloadOutlined />}
            onClick={() => actionRef.current?.reload()}
          >
            刷新
          </Button>,
        ].filter(Boolean)}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        scroll={{ x: 1500 }}
      />

      {/* 编辑用户Modal */}
      <Modal
        title={`编辑用户 - ${editingUser?.username || ''}`}
        open={editVisible}
        onCancel={() => {
          setEditVisible(false);
          setEditingUser(null);
          editForm.resetFields();
          setActiveTab('basic');
        }}
        footer={null}
        width={800}
      >
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={[
            {
              key: 'basic',
              label: '基本信息',
              children: (
                <ProForm
                  form={editForm}
                  onFinish={handleSaveEdit}
                  submitter={{
                    searchConfig: {
                      submitText: '保存',
                      resetText: '取消',
                    },
                    submitButtonProps: {
                      loading: editLoading,
                      icon: <SaveOutlined />,
                    },
                    resetButtonProps: {
                      onClick: () => {
                        setEditVisible(false);
                        setEditingUser(null);
                        editForm.resetFields();
                        setActiveTab('basic');
                      },
                    },
                  }}
                >
                  <ProFormText
                    name="username"
                    label="用户名"
                    disabled
                    tooltip="用户名不可修改"
                  />

                  <ProFormText
                    name="email"
                    label="邮箱"
                    rules={[
                      { required: true, message: '请输入邮箱' },
                      { type: 'email', message: '请输入有效的邮箱地址' },
                    ]}
                  />

                  <ProFormText
                    name="first_name"
                    label="名"
                  />

                  <ProFormText
                    name="last_name"
                    label="姓"
                  />

                  <ProFormSwitch
                    name="is_active"
                    label="是否激活"
                    tooltip="禁用后用户将无法登录"
                  />

                  <ProFormSwitch
                    name="is_staff"
                    label="管理员权限"
                    tooltip="管理员可以访问后台管理界面"
                  />
                </ProForm>
              ),
            },
            {
              key: 'groups',
              label: `组管理 (${selectedGroups.length})`,
              children: (
                <div>
                  <Transfer
                    dataSource={(allGroups || []).map(group => ({
                      key: group?.id?.toString() || '',
                      title: group?.name || '',
                      description: group?.profile?.display_name || group?.name || '',
                    })).filter(item => item.key !== '')}
                    targetKeys={(selectedGroups || []).filter(id => id != null).map(id => id.toString())}
                    onChange={(newTargetKeys, direction, moveKeys) => {
                      console.log('🔄 组变更:', { newTargetKeys, direction, moveKeys });
                      const newSelectedGroups = newTargetKeys.map(key => parseInt(key.toString(), 10));
                      console.log('🎯 新组数组:', newSelectedGroups);
                      setSelectedGroups(newSelectedGroups);
                    }}
                    render={item => (
                      <div>
                        <div>{item.title}</div>
                        <div style={{ fontSize: '11px', color: '#999' }}>{item.description}</div>
                      </div>
                    )}
                    titles={['可选组', '已分配组']}
                    showSearch
                    filterOption={(inputValue, option) =>
                      option.title.toLowerCase().includes(inputValue.toLowerCase()) ||
                      option.description.toLowerCase().includes(inputValue.toLowerCase())
                    }
                    listStyle={{
                      width: 300,
                      height: 400,
                    }}
                  />
                  <div style={{ marginTop: 16, textAlign: 'center' }}>
                    <Button
                      type="primary"
                      loading={editLoading}
                      onClick={handleSaveUserGroups}
                    >
                      保存组分配
                    </Button>
                  </div>
                </div>
              ),
            },
            {
              key: 'permissions',
              label: `权限管理 (${selectedPermissions.length})`,
              children: (
                <div>
                  <Transfer
                    dataSource={(allPermissions || []).map(permission => ({
                      key: permission?.id?.toString() || '',
                      title: permission?.name || '',
                      description: `${permission?.content_type_name || ''} | ${permission?.codename || ''}`,
                    })).filter(item => item.key !== '')}
                    targetKeys={(selectedPermissions || []).filter(id => id != null).map(id => id.toString())}
                    onChange={(newTargetKeys, direction, moveKeys) => {
                      console.log('🔄 权限变更:', { newTargetKeys, direction, moveKeys });
                      const newSelectedPermissions = newTargetKeys.map(key => parseInt(key.toString(), 10));
                      console.log('🎯 新权限数组:', newSelectedPermissions);
                      setSelectedPermissions(newSelectedPermissions);
                    }}
                    render={item => (
                      <div>
                        <div>{item.title}</div>
                        <div style={{ fontSize: '11px', color: '#999' }}>{item.description}</div>
                      </div>
                    )}
                    titles={['可选权限', '已分配权限']}
                    showSearch
                    filterOption={(inputValue, option) =>
                      option.title.toLowerCase().includes(inputValue.toLowerCase()) ||
                      option.description.toLowerCase().includes(inputValue.toLowerCase())
                    }
                    listStyle={{
                      width: 300,
                      height: 400,
                    }}
                  />
                  <div style={{ marginTop: 16, textAlign: 'center' }}>
                    <Button
                      type="primary"
                      loading={editLoading}
                      onClick={handleSaveUserPermissions}
                    >
                      保存权限分配
                    </Button>
                  </div>
                </div>
              ),
            },
          ]}
        />
      </Modal>
    </PageContainer>
  );
};

export default UserListNew;
